package com.MTteam.activities;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.MTteam.control.HDK_Library_ReaderLogin;
import com.MTteam.control.HDK_Library_Searching;
import com.MTteam.hdk.R;
import com.actionbarsherlock.app.SherlockActivity;
import com.devspark.appmsg.AppMsg;
import com.tendcloud.tenddata.TCAgent;

public class HDK_Library_Activity extends SherlockActivity {

	private Button library_bt_lastPage, library_bt_nextPage, library_bt_login;
	private DrawerLayout mDrawerLayout;
	private EditText library_et_bookname, library_et_readerNo,
			library_et_readerPwd;
	private TextView search_count;
	private ListView library_list;

	private String bookItem, bookUrl, bookPress, bookDate, bookISBN,
			bookSuoshuhao, bookPage;

	private String lastPage, nextPage;
	private ProgressDialog mDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_hdk_library);
		TCAgent.setReportUncaughtExceptions(true);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setTitle("图书�?");

		library_et_bookname = (EditText) findViewById(R.id.library_et_bookname);

		library_bt_lastPage = (Button) findViewById(R.id.library_bt_lastPage);
		library_bt_nextPage = (Button) findViewById(R.id.library_bt_nextPage);

		library_list = (ListView) findViewById(R.id.search_list);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

		mDialog = new ProgressDialog(this);
		mDialog.setTitle("正在加载...");
		mDialog.setMessage("温馨提示:由于�?��访问网络,加载会比较慢,如果长时间不能获取数�?可返回重新加�?建议您在wifi状�?下使�?效果会�?�?");
		mDialog.setCanceledOnTouchOutside(false);

		Button mButton = (Button) findViewById(R.id.library_bt_find);
		mButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				String bookName = library_et_bookname.getText().toString()
						.trim();
				Intent intent = new Intent(HDK_Library_Activity.this,
						HDK_Library_Searching.class);
				intent.putExtra("bookName", bookName);
				startActivityForResult(intent, 1);
			}
		});

		library_list.setOnItemClickListener(new onListItemClickListener());

		library_bt_lastPage.setOnClickListener(new lastPageButtonClick());
		library_bt_nextPage.setOnClickListener(new nextPageButtonClick());

		library_et_readerNo = (EditText) findViewById(R.id.library_et_readerNo);
		library_et_readerPwd = (EditText) findViewById(R.id.library_et_readerPwd);

		library_bt_login = (Button) findViewById(R.id.library_bt_login);

		library_bt_login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if ("".equals(library_et_readerNo.getText().toString().trim())
						|| "".equals(library_et_readerPwd.getText().toString()
								.trim())) {
					AppMsg.makeText(HDK_Library_Activity.this, "您还没有填写完整!",
							AppMsg.STYLE_INFO).show();
				} else {
					Intent intent = new Intent(HDK_Library_Activity.this,
							HDK_Library_ReaderLogin.class);
					intent.putExtra("readerNo", library_et_readerNo.getText()
							.toString().trim());
					intent.putExtra("readerPwd", library_et_readerPwd.getText()
							.toString().trim());
					startActivityForResult(intent, 2);
				}
			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent result) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, result);
		if (resultCode == 1) {
			String searchResult = result.getExtras().getString("searchResult");
			search_count = (TextView) findViewById(R.id.search_count);
			if (searchResult.contains("seek.hzu.edu.cn")) {
				search_count.setText("没有找到任何结果！请重试");
			} else {
				search_count.setText("\u3000\u3000" + searchResult);

				lastPage = result.getExtras().getString("lastPage");
				nextPage = result.getExtras().getString("nextPage");

				ArrayList<HashMap<String, String>> bookList = new ArrayList<HashMap<String, String>>();
				bookList = (ArrayList<HashMap<String, String>>) result
						.getSerializableExtra("bookList");

				if (bookList != null) {
					SimpleAdapter bookListAdapter = new SimpleAdapter(this,
							bookList, R.drawable.library_list_item,
							new String[] { "bookItem", "bookUrl", "press",
									"date", "ISBN", "suoshuhao", "page" },
							new int[] { R.id.library_item_book,
									R.id.library_item_url,
									R.id.library_item_press,
									R.id.library_item_date,
									R.id.library_item_ISBN,
									R.id.library_item_suoshuhao,
									R.id.library_item_page });
					library_list.setAdapter(bookListAdapter);
					library_list.setLayoutAnimation(getListAnim());
				}
			}

			mDrawerLayout.openDrawer(Gravity.LEFT);
		}

		if (resultCode == 2) {
			if ("FALSE".equals(result.getStringExtra("FALSEorSUCCESS"))) {
				AppMsg.makeText(HDK_Library_Activity.this, "登录失败!",
						AppMsg.STYLE_ALERT).show();
			}
			if ("SUCCESS".equals(result.getStringExtra("FALSEorSUCCESS"))) {
				String No = result.getExtras().getString("No");
				String Pwd = result.getExtras().getString("Pwd");
				String Name = result.getExtras().getString("Name");
				String Sex = result.getExtras().getString("Sex");
				String Address = result.getExtras().getString("Address");
				String Kind = result.getExtras().getString("Kind");
				String Date = result.getExtras().getString("Date");
				String YE = result.getExtras().getString("YE");
				String Zhuantai = result.getExtras().getString("Zhuantai");

				ArrayList<HashMap<String, String>> readerBookList = new ArrayList<HashMap<String, String>>();
				readerBookList = (ArrayList<HashMap<String, String>>) result
						.getSerializableExtra("readerBookList");
				Intent intent = new Intent(HDK_Library_Activity.this,
						HDK_Library_Reader_Book_Activity.class);
				intent.putExtra("No", No);
				intent.putExtra("Pwd", Pwd);
				intent.putExtra("Name", Name);
				intent.putExtra("Sex", Sex);
				intent.putExtra("Address", Address);
				intent.putExtra("Kind", Kind);
				intent.putExtra("Date", Date);
				intent.putExtra("YE", YE);
				intent.putExtra("Zhuantai", Zhuantai);
				intent.putExtra("readerBookList", readerBookList);

				startActivity(intent);
			}
		}

	}

	private LayoutAnimationController getListAnim() {
		AnimationSet set = new AnimationSet(true);
		Animation animation = new AlphaAnimation(0.0f, 1.0f);
		animation.setDuration(300);
		set.addAnimation(animation);

		animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				-1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
		animation.setDuration(500);
		set.addAnimation(animation);
		LayoutAnimationController controller = new LayoutAnimationController(
				set, 0.5f);
		return controller;
	}

	public class onListItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			TextView temp1 = (TextView) arg1
					.findViewById(R.id.library_item_book);
			TextView temp2 = (TextView) arg1
					.findViewById(R.id.library_item_url);
			TextView temp3 = (TextView) arg1
					.findViewById(R.id.library_item_press);
			TextView temp4 = (TextView) arg1
					.findViewById(R.id.library_item_date);
			TextView temp5 = (TextView) arg1
					.findViewById(R.id.library_item_ISBN);
			TextView temp6 = (TextView) arg1
					.findViewById(R.id.library_item_suoshuhao);
			TextView temp7 = (TextView) arg1
					.findViewById(R.id.library_item_page);
			bookItem = temp1.getText().toString();
			bookUrl = temp2.getText().toString();
			bookPress = temp3.getText().toString();
			bookDate = temp4.getText().toString();
			bookISBN = temp5.getText().toString();
			bookSuoshuhao = temp6.getText().toString();
			bookPage = temp7.getText().toString();

			mDialog.show();
			new Thread(searchBookAbout).start();
		}
	}

	Runnable searchBookAbout = new Runnable() {

		List<HashMap<String, String>> resultListTemp = new ArrayList<HashMap<String, String>>();

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Document doc;
			try {
				resultListTemp.clear();
				doc = (Document) Jsoup.connect(bookUrl).timeout(60000).get();

				for (Element ele2 : doc.getElementsByTag("table").last()
						.select("tbody > tr")) {
					String number = null;
					String shuku = null;
					String dengluhao = null;
					String leibie = null;
					String qi = null;
					String juan = null;
					String price = null;
					String zhuandin = null;
					String liutong = null;
					String pinlv = null;
					if (!ele2.select("td").toString().equals("")) {
						if (ele2.select("td").get(0).text().toString()
								.equals("序号")) {
							number = ele2.select("td").get(0).text().toString();
							shuku = ele2.select("td").get(1).text().toString();
							dengluhao = ele2.select("td").get(2).text()
									.toString();
							leibie = ele2.select("td").get(3).text().toString();
							qi = ele2.select("td").get(4).text().toString();
							juan = ele2.select("td").get(5).text().toString();
							price = ele2.select("td").get(6).text().toString();
							zhuandin = ele2.select("td").get(7).text()
									.toString();
							liutong = ele2.select("td").get(8).text()
									.toString()
									+ " "
									+ ele2.select("td").get(9).text()
											.toString();
							pinlv = ele2.select("td").get(10).text().toString();
						}

						if (ele2.select("td").get(8).text().toString()
								.contains("借出")) {
							number = ele2.select("td").get(0).text().toString();
							shuku = ele2.select("td").get(1).text().toString();
							dengluhao = ele2.select("td").get(2).text()
									.toString();
							leibie = ele2.select("td").get(3).text().toString();
							qi = ele2.select("td").get(4).text().toString();
							juan = ele2.select("td").get(5).text().toString();
							price = ele2.select("td").get(6).text().toString();
							zhuandin = ele2.select("td").get(7).text()
									.toString();
							liutong = ele2.select("td").get(8).text()
									.toString();
							pinlv = ele2.select("td").get(9).text().toString();
						}
						if (ele2.select("td").get(8).text().toString()
								.contains("在编")) {
							number = ele2.select("td").get(0).text().toString();
							shuku = ele2.select("td").get(1).text().toString();
							dengluhao = ele2.select("td").get(2).text()
									.toString();
							leibie = ele2.select("td").get(3).text().toString();
							qi = ele2.select("td").get(4).text().toString();
							juan = ele2.select("td").get(5).text().toString();
							price = ele2.select("td").get(6).text().toString();
							zhuandin = ele2.select("td").get(7).text()
									.toString();
							liutong = ele2.select("td").get(8).text()
									.toString();
							pinlv = ele2.select("td").get(9).text().toString();
						}
						if (ele2.select("td").get(8).text().toString()
								.contains("入藏")) {
							number = ele2.select("td").get(0).text().toString();
							shuku = ele2.select("td").get(1).text().toString();
							dengluhao = ele2.select("td").get(2).text()
									.toString();
							leibie = ele2.select("td").get(3).text().toString();
							qi = ele2.select("td").get(4).text().toString();
							juan = ele2.select("td").get(5).text().toString();
							price = ele2.select("td").get(6).text().toString();
							zhuandin = ele2.select("td").get(7).text()
									.toString();
							liutong = ele2.select("td").get(8).text()
									.toString()
									+ " "
									+ ele2.select("td").get(9).text()
											.toString();
							pinlv = ele2.select("td").get(10).text().toString();
						}

						HashMap<String, String> listitem = new HashMap<String, String>();
						listitem.put("number", number);
						listitem.put("shuku", shuku);
						listitem.put("dengluhao", dengluhao);
						listitem.put("leibie", leibie);
						listitem.put("qi", qi);
						listitem.put("juan", juan);
						listitem.put("price", price);
						listitem.put("zhuandin", zhuandin);
						listitem.put("liutong", liutong);
						listitem.put("pinlv", pinlv);
						resultListTemp.add(listitem);
					}
				}

				Message msg1 = new Message();
				Bundle data = new Bundle();
				// data.putStringArray("aboutArray", aboutArray);
				msg1.setData(data);
				msg1.obj = resultListTemp;
				bookResult.sendMessage(msg1);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	Handler bookResult = new Handler() {

		@Override
		public void handleMessage(Message msg1) {
			// TODO Auto-generated method stub
			super.handleMessage(msg1);
			Bundle data = msg1.getData();
			// String[] aboutArray = data.getStringArray("aboutArray");
			ArrayList<HashMap<String, String>> resultListTemp = (ArrayList<HashMap<String, String>>) msg1.obj;
			Intent intent = new Intent(HDK_Library_Activity.this,
					HDK_Library_Result_Activity.class);
			// intent.putExtra("searchResult", aboutArray);
			intent.putExtra("resultListTemp", resultListTemp);
			intent.putExtra("bookItem", bookItem);
			intent.putExtra("bookPress", bookPress);
			intent.putExtra("bookDate", bookDate);
			intent.putExtra("bookISBN", bookISBN);
			intent.putExtra("bookSuoshuhao", bookSuoshuhao);
			intent.putExtra("bookPage", bookPage);
			mDialog.dismiss();
			startActivity(intent);
		}

	};

	public class lastPageButtonClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			if (lastPage == null) {
				AppMsg.makeText(HDK_Library_Activity.this, "没有上一页了",
						AppMsg.STYLE_INFO).show();
			} else {
				lastPage = lastPage.substring(3);
				String bookName = lastPage;
				try {
					bookName = URLDecoder.decode(bookName, "GB2312");
					Intent intent = new Intent(HDK_Library_Activity.this,
							HDK_Library_Searching.class);
					intent.putExtra("bookName", bookName);
					startActivityForResult(intent, 1);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
	}

	public class nextPageButtonClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			if (nextPage == null) {
				AppMsg.makeText(HDK_Library_Activity.this, "没有下一页了",
						AppMsg.STYLE_INFO).show();
			} else {
				nextPage = nextPage.substring(3);
				String bookName = nextPage;
				try {
					bookName = URLDecoder.decode(bookName, "GB2312");
					Intent intent = new Intent(HDK_Library_Activity.this,
							HDK_Library_Searching.class);
					intent.putExtra("bookName", bookName);
					startActivityForResult(intent, 1);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}

	}

	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			if (mDrawerLayout.isDrawerOpen(Gravity.LEFT) == true) {
				mDrawerLayout.closeDrawer(Gravity.LEFT);
			} else {
				finish();
			}
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void onResume() {
		super.onResume();
		TCAgent.onResume(this);
	};

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		TCAgent.onPause(this);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getRepeatCount() == 0) {
			if (mDrawerLayout.isDrawerOpen(Gravity.LEFT) == true) {
				mDrawerLayout.closeDrawer(Gravity.LEFT);
			} else {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
